package cn.itcast.bos.action.take_delivery;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import cn.itcast.bos.domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.utils.BaseAction;

public class PromotionAction extends BaseAction<Promotion> {

	private File titleImgFile;
	private String titleImgFileFileName;

	public void setTitleImgFile(File titleImgFile) {
		this.titleImgFile = titleImgFile;
	}

	public void setTitleImgFileFileName(String titleImgFileFileName) {
		this.titleImgFileFileName = titleImgFileFileName;
	}
	
	@Autowired
	private PromotionService promotionService;
	

	@Action(value = "promotion_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/take_delivery/promotion.html") })
	public String savePromotion() throws IOException {
		// 图片保存的磁盘绝对路径
		String savePath = ServletActionContext.getServletContext().getRealPath("/upload");
		// 图片保存显示的项目相对路径
		String urlPath = ServletActionContext.getRequest().getContextPath() + "/upload/";

		// 获取文件的后缀名
		String ext = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
		// 保存的文件名
		String filename = UUID.randomUUID() + ext;

		// 保存图片
		File file = new File(savePath + "/" + filename);
		if (titleImgFile != null) {
			FileUtils.copyFile(titleImgFile, file);
		}
		
		model.setTitleImg(urlPath+filename);
		
		promotionService.save(model);
		return SUCCESS;
	}
	
	private Integer page;
	private Integer rows;
	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}
	//无条件分页查询宣传
	@Action(value="promotion_pagequery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		Pageable pageable = new PageRequest(page-1, rows);
		Page<Promotion> page = promotionService.pageQuery(pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;
	}
}
